﻿using System;
using System.Net;
using System.Net.Mail;
using System.Net.Mime;
using System.IO;
using System.Text;

namespace WFBASE
{
    /// <summary>  
    /// 发送邮件的类 
    /// </summary>  
    public class SendMail
    {
        private MailMessage mailMessage;
        private SmtpClient smtpClient;
        private string password;//发件人密码  
        private string smtpHost;

        public SendMail()
        {
            mailMessage = new MailMessage();
            SetSMTPServer();
        }

        #region System Error Reporter
        public void SendSysReport(string p_Body)
        {
            /*string fromMail = System.Configuration.ConfigurationManager.AppSettings["WebMasterMail"].ToString();
            string toMail = System.Configuration.ConfigurationManager.AppSettings["WebMailReciever"];
            if (toMail == null || toMail.Trim() == "")
                toMail = fromMail;
            SendHtmlMail(fromMail, toMail, "", "System Error Report", p_Body);*/
            WriteLogs(p_Body);
        }
        public void SendTextSysReport(string p_Body)
        {
            SendSysReport(p_Body);
        }
        #endregion

        #region 发送邮件的设定程式
        /// <summary>
        /// 发送不需要验证的邮件
        /// </summary>
        /// <param name="p_From"></param>
        /// <param name="p_To"></param>
        /// <param name="p_Cc"></param>
        /// <param name="p_Title"></param>
        /// <param name="p_Body"></param>
        public void SendHtmlMail(string p_From, string p_To, string p_Cc, string p_Title, string p_Body)
        {
            SetMailTo(p_To);
            SetMailCc(p_Cc);
            mailMessage.From = new System.Net.Mail.MailAddress(p_From);
            //if (p_Cc != null && p_Cc != "")
            //    mailMessage.CC.Add(p_Cc);
            mailMessage.Subject = p_Title;
            mailMessage.Body = p_Body;
            mailMessage.IsBodyHtml = true;
            mailMessage.BodyEncoding = System.Text.Encoding.UTF8;
            mailMessage.Priority = System.Net.Mail.MailPriority.Normal;
            this.Send();
        }
        void SetMailTo(string p_To)
        {
            mailMessage.To.Clear();
            if (p_To == null || p_To == "")
                return;
            if (p_To.IndexOf(",") != -1)
            {
                for (int i = 0; i < p_To.Split(',').Length; i++)
                {
                    if (p_To.Split(',')[i] != "")
                    {
                        try
                        {
                            mailMessage.To.Add(new MailAddress(p_To.Split(',')[i]));
                        }
                        catch (Exception ex) { throw new Exception("Error mail address:"+p_To); }
                    }
                }
            }
            else if (p_To.IndexOf(";") != -1)
            {
                for (int i = 0; i < p_To.Split(';').Length; i++)
                    if (p_To.Split(';')[i] != "")
                    {
                        try
                        {
                            mailMessage.To.Add(new MailAddress(p_To.Split(';')[i]));
                        }
                        catch (Exception ex) { throw new Exception("Error mail address:" + p_To); }
                    }
            }
            else
                mailMessage.To.Add(new MailAddress(p_To));
        }
        void SetMailCc(string p_Cc)
        {
            mailMessage.CC.Clear();
            if (p_Cc == null || p_Cc == "")
                return;
            if (p_Cc.IndexOf(",") != -1)
            {
                for (int i = 0; i < p_Cc.Split(',').Length; i++)
                    if(p_Cc.Split(',')[i]!="")
                        mailMessage.CC.Add(p_Cc.Split(',')[i]);
            }
            else if (p_Cc.IndexOf(";") != -1)
            {
                for (int i = 0; i < p_Cc.Split(';').Length; i++)
                    if (p_Cc.Split(';')[i] != "")
                        mailMessage.CC.Add(p_Cc.Split(';')[i]);
            }
            else
                mailMessage.CC.Add(p_Cc);
        }
        public void SendHtmlMail(string p_From, string p_To, string p_Title, string p_Body)
        {
            SendHtmlMail(p_From, p_To, "", p_Title, p_Body);
        }
        public void SendHtmlMail(string p_To, string p_Title, string p_Body)
        {
            string fromMail = System.Configuration.ConfigurationManager.AppSettings["WebMasterMail"].ToString();
            SendHtmlMail(fromMail, p_To, "", p_Title, p_Body);
        }
        /// <summary>
        /// 缺少只有To和Cc的方法，故而新增
        /// Created by fans 2009-6-9
        /// </summary>
        /// <param name="p_To"></param>
        /// <param name="p_Cc"></param>
        /// <param name="p_Title"></param>
        /// <param name="p_Body"></param>
        public void SendHtmlMailCc(string p_To, string p_Cc, string p_Title, string p_Body)
        {
            string fromMail = System.Configuration.ConfigurationManager.AppSettings["WebMasterMail"].ToString();
            SendHtmlMail(fromMail, p_To, p_Cc, p_Title, p_Body);
        }

        /// <summary>
        /// 发送需要验证的邮件
        /// </summary>
        /// <param name="p_From"></param>
        /// <param name="p_To"></param>
        /// <param name="p_Title"></param>
        /// <param name="p_Body"></param>
        /// <param name="p_Password"></param>
        public void SendCredentialMail(string p_From, string p_To, string p_Title, string p_Body, string p_Password)
        {
            mailMessage.To.Add(p_To);
            mailMessage.From = new System.Net.Mail.MailAddress(p_From);
            mailMessage.Subject = p_Title;
            mailMessage.Body = p_Body;
            mailMessage.IsBodyHtml = true;
            mailMessage.BodyEncoding = System.Text.Encoding.UTF8;
            mailMessage.Priority = System.Net.Mail.MailPriority.Normal;
            this.password = p_Password;
            this.SendCredential();
        }
        #endregion

        #region Settings
        public void SetSMTPServer()
        {
            this.smtpHost = System.Configuration.ConfigurationManager.AppSettings["WebMailServer"];
            if (this.smtpHost == null || this.smtpHost.Trim() == "")
                this.smtpHost = "172.18.5.3";

        }
        public void SetSmtpServer(string p_SmtpIp)
        {
            this.smtpHost = p_SmtpIp;
        }
        /// <summary>  
        /// 添加附件  
        /// </summary>  
        public void Attachments(string Path)
        {
            string[] path = Path.Split(',');
            Attachment data;
            ContentDisposition disposition;
            for (int i = 0; i < path.Length; i++)
            {
                data = new Attachment(path[i], MediaTypeNames.Application.Octet);//实例化附件 
                disposition = data.ContentDisposition;
                disposition.CreationDate = System.IO.File.GetCreationTime(path[i]);//获取附件的创 建日期 
                disposition.ModificationDate = System.IO.File.GetLastWriteTime(path[i]);//获取附件的修改日期 
                disposition.ReadDate = System.IO.File.GetLastAccessTime(path[i]);//获取附件的读 取日期 
                mailMessage.Attachments.Add(data);//添加到附件中 
            }
        }
        #endregion

        #region 最终发送邮件的程式
        /// <summary>  
        /// 非同步发 送邮 件 
        /// </summary>  
        /// <param name="CompletedMethod"></param>  
        public void SendAsync(SendCompletedEventHandler CompletedMethod)
        {
            if (mailMessage != null)
            {
                smtpClient = new SmtpClient();
                smtpClient.Credentials = new System.Net.NetworkCredential(mailMessage.From.Address, password);//设置发 件人身份的票据 
                smtpClient.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
                //smtpClient.Host = "smtp." + mailMessage.From.Host;
                smtpClient.Host = this.smtpHost;
                smtpClient.SendCompleted += new SendCompletedEventHandler(CompletedMethod);//注册 非同步发 送邮 件完成时 的事件 
                smtpClient.SendAsync(mailMessage, mailMessage.Body);
            }
        }

        /// <summary>  
        /// 不需要票据发邮件 
        /// </summary>  
        public void Send()
        {
            try
            {
                if (mailMessage != null)
                {
                    smtpClient = new SmtpClient();
                    smtpClient.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
                    smtpClient.Host = this.smtpHost;
                    smtpClient.Send(mailMessage);
                }
            }
            catch (Exception ex)//当发送邮件不成功时，记录此信息到服务器Log文件  2010-3-3 by fans
            {
                WriteLogs(ex.ToString());
            }
        }

        /// <summary>
        /// 需要票据发邮件
        /// </summary>
        public void SendCredential()
        {
            if (mailMessage != null)
            {
                smtpClient = new SmtpClient();
                smtpClient.Credentials = new System.Net.NetworkCredential(mailMessage.From.Address, password);//设置发 件人身份的票据 
                smtpClient.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
                smtpClient.Host = this.smtpHost;
                smtpClient.Send(mailMessage);
            }
        }
        #endregion

        public void WriteLogs(string p_Body)
        {
            string fpath = System.Configuration.ConfigurationManager.AppSettings["uploadfilePath"].ToString() +
                "..\\..\\inc\\tree\\log" + System.DateTime.Now.ToString("yyyyMMdd") + ".log";
            string uid = "";// System.Web.HttpContext.Current.User.Identity.Name;
            StreamWriter sw = new StreamWriter(fpath, true, Encoding.Default);
            string msg = System.DateTime.Now.ToString("yyyy/MM/dd-hh:mm:ss") + "----uid:" + uid + "-----";
            sw.WriteLine(msg);
            sw.Write(p_Body);
            sw.WriteLine("");
            sw.Flush();
            sw.Close();
            sw.Dispose();
        }


        /// <summary>
        /// 3.0新格式Email发送方法
        /// </summary>
        //public void SendNewMailCN(string MailTo, string MailCC,string MailBCC,string MailSubject,string MailContent, string MailStatus)
        //{
        //    MailMessage mm = new MailMessage();
        //    MailAddress MailFrom = new MailAddress(System.Configuration.ConfigurationManager.AppSettings["WebMasterMail"].ToString());  
        //    mm.To.Add(MailTo);
        //    mm.CC.Add(MailCC);
        //    mm.Bcc.Add(MailBCC);
        //    mm.Subject = MailSubject;
        //    string content = "";
        //    //string content = "<center>" +
        //    //                      "<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" style=\"background-color: #FFF; border: solid 2px #E5E5E5; min-width: 430px; width: 700px;\"> " +
        //    //                          "<tr>" +
        //    //                              "<td>" +
        //    //                                  "<div style=\"height: 75px; background-image: url(cid:Email001); white-space: nowrap; width: 100%;\"> " +
        //    //                                      "<div style=\"height: 75px; background-image: url(cid:Email002); background-repeat: no-repeat;float: left; position: relative; width: 240px;\">" +
        //    //                                      "</div>" +
        //    //                                      "<div style=\"height: 75px; background-image: url(cid:Email003);background-repeat: no-repeat; float: right; position: relative; width: 240px;\">" +
        //    //                                          "<div style=\"color: #F5FE00; font-size: 16px; font-family: 新细明体; font-weight: bolder;position: relative; top: 42px; left: 100px;\">" + MailStatus + "</div>" +
        //    //                                      "</div>" +
        //    //                                  "</div>" +
        //    //                              "</td>" +
        //    //                          "</tr>" +
        //    //                          "<tr>" +
        //    //                              "<td>" + MailContent + "</td>" +
        //    //                          "</tr>" +
        //    //                          "<tr>" +
        //    //                              "<td style=\"height: 196px; background-image: url(cid:Email004);background-position: bottom; background-repeat: repeat-x; position: relative;\">" +
        //    //                                  "<div style=\"height: 196px; background-image: url(cid:Email005);background-position: right; background-repeat: no-repeat; white-space: nowrap;width: 100%;\">" +
        //    //                                      "<div style=\"color: #5E5E5E; font-family: 新细明体; font-size: 16px; text-align: left;white-space: nowrap; position: relative; float: left; left: 20px; width: 100%;margin-top: 30px; line-height: 25px;\">" +
        //    //                                          "网站链接：若你目前上网地点<br />" +
        //    //                                          "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;1." +
        //    //                                          "在集团公司内请点击“<a href=\"#\">电子签核系统(内部网)</a>”<br />" +
        //    //                                          "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;2." +
        //    //                                          "在集团公司外请点击“<a href=\"#\">电子签核系统(外部网)</a>”<br />" +
        //    //                                          "备 注： 进入网站后请点击 “<font color=\"blue\">电子签核系统</font>”的 “<font color=\"blue\">待审核单据</font>”检视。" +
        //    //                                      "</div>" +
        //    //                                      "<div style=\"text-align: left; white-space: nowrap; position: relative; float: left;left: 20px; margin-top: 5px; width: 100%; height: 26px; background-image: url(cid:Email006);background-repeat: no-repeat;\">" +
        //    //                                      "</div>" +
        //    //                                      "<div style=\"color: #5E5E5E; font-family: 新细明体; font-size: 16px; text-align: left;white-space: nowrap; position: relative; float: left; left: 20px; margin-top: 10px;\">" +
        //    //                                          "若您有任何问题，请点击 “<a href=\"#\" style=\"color: #E15403;\"><b>客服信箱</b></a>” 与客服专员联系。" +
        //    //                                      "</div>" +
        //    //                                  "</div>" +
        //    //                              "</td>" +
        //    //                          "</tr>" +
        //    //                      "</table>" +
        //    //                  "</center>";
        //    AlternateView htmlBody = AlternateView.CreateAlternateViewFromString(content, null, "text/html");

        //    string FilePath = System.Configuration.ConfigurationManager.AppSettings["EmailIMGPath"].ToString();

        //    LinkedResource lrImage = new LinkedResource(FilePath+"titlebg.jpg", "image/gif");
        //    lrImage.ContentId = "Email001";
        //    LinkedResource lrImage2 = new LinkedResource(FilePath+"logo.jpg", "image/gif");
        //    lrImage2.ContentId = "Email002";
        //    LinkedResource lrImage3 = new LinkedResource(FilePath+"titleleft.jpg", "image/gif");
        //    lrImage3.ContentId = "Email003";
        //    LinkedResource lrImage4 = new LinkedResource(FilePath+"bottom.jpg", "image/gif");
        //    lrImage4.ContentId = "Email004";
        //    LinkedResource lrImage5 = new LinkedResource(FilePath+"bottomlogo.jpg", "image/gif");
        //    lrImage5.ContentId = "Email005";
        //    LinkedResource lrImage6 = new LinkedResource(FilePath+"remark.gif", "image/gif");
        //    lrImage6.ContentId = "Email006";
        //    htmlBody.LinkedResources.Add(lrImage);
        //    htmlBody.LinkedResources.Add(lrImage2);
        //    htmlBody.LinkedResources.Add(lrImage3);
        //    htmlBody.LinkedResources.Add(lrImage4);
        //    htmlBody.LinkedResources.Add(lrImage5);
        //    htmlBody.LinkedResources.Add(lrImage6);
        //    mm.AlternateViews.Add(htmlBody);

        //    SmtpClient smtp = new SmtpClient();
        //    smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
        //    smtp.Host = System.Configuration.ConfigurationManager.AppSettings["WebMailServer"].ToString();
        //    smtp.Send(mm);
        //}
    }
}
